package com.jiezuo.auth.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jiezuo.auth.entity.*;
import com.jiezuo.auth.service.DepartService;
import com.jiezuo.auth.service.UserRoleService;
import com.jiezuo.auth.service.UserService;
import com.jiezuo.common.annotation.RepeatSubmit;
import com.jiezuo.common.base.BaseController;
import com.jiezuo.common.constant.SysConstant;
import com.jiezuo.common.enums.ResultEnums;
import com.jiezuo.common.util.*;
import com.jiezuo.common.vo.PageVo;
import com.jiezuo.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 庞留杰
 * @version V1.0
 * @description 用户管理
 * @date 2020/7/23 8:59
 **/

@Slf4j
@RequestMapping("/user")
@RestController
@Transactional
//用户管理", tags = {"用户管理接口"})
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private DepartService departService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //读取文件路径
    @Value("${file.file-read-path}")
    private String fileReadPath;

    //查询带分页列表", notes = "查询带分页列表")
    @GetMapping("/findPage")
    public Result<IPage<User>> findPage(@ModelAttribute PageVo pageVo, @ModelAttribute User user) {
        IPage<User> page = userService.findPage(PageUtil.initMpPage(pageVo), user);
        for (User u : page.getRecords()) {
            //拼接头像
            u.setAvatar(fileReadPath + u.getAvatar());
            //通过用户查询部门
            List<Depart> departs = userService.getDepartsByUserId(u.getId());
            u.setDepts(departs);
            //通过用户查询角色
            List<Role> roles = userService.getRolesByUserId(u.getId());
            u.setRoles(roles);
        }
        return new ResultUtil<IPage<User>>().setData(page);
    }

    //通过部门ids查询带分页列表", notes = "通过部门ids查询带分页列表")
    @GetMapping("/findPageByDeptIds")
    public Result<IPage<User>> findPageByDeptIds(@ModelAttribute PageVo pageVo, @ModelAttribute User user) {
        IPage<User> page = userService.findPage(PageUtil.initMpPage(pageVo), user);
        for (User u : page.getRecords()) {
            //拼接头像
            u.setAvatar(fileReadPath + u.getAvatar());
            //通过用户查询部门
            List<Depart> departs = userService.getDepartsByUserId(u.getId());
            u.setDepts(departs);
            //通过用户查询角色
            List<Role> roles = userService.getRolesByUserId(u.getId());
            u.setRoles(roles);
        }
        return new ResultUtil<IPage<User>>().setData(page);
    }


    //查询不带分页列表", notes = "查询不带分页列表")
    @GetMapping("/findList")
    public Result<List<User>> findList(@ModelAttribute User user) {
        List<User> list = userService.findList(user);
        for (User u : list) {
            //拼接头像
            u.setAvatar(fileReadPath + u.getAvatar());
            //通过用户查询部门
            List<Depart> departs = userService.getDepartsByUserId(u.getId());
            u.setDepts(departs);
            //通过用户查询角色
            List<Role> roles = userService.getRolesByUserId(u.getId());
            u.setRoles(roles);
        }
        return new ResultUtil<List<User>>().setData(list);
    }

    //查询所有用户列表", notes = "查询所有用户列表")
    @GetMapping("/findAllList")
    public Result<List<User>> findAllList(@ModelAttribute User user) {
        List<User> list = userService.findList(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    //部门及部门以下查询不带分页列表(技术标和工作联系函)", notes = "部门及部门以下查询不带分页列表(技术标和工作联系函)")
    @GetMapping("/findDepartDownList")
    public Result<List<User>> findDepartDownList(@ModelAttribute User user) {
        //传过来是pid 还需查询下边是否还有子部门 如果有的话需要把下边人员一并查出来
        List<User> list = userService.findDepartDownList(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    //部门及部门以下查询不带分页列表(项目联系函)", notes = "部门及部门以下查询不带分页列表(项目联系函)")
    @GetMapping("/findChargeList")
    public Result<List<User>> findChargeList(@ModelAttribute User user) {
        //传过来是pid 还需查询下边是否还有子部门 如果有的话需要把下边人员一并查出来
        List<User> list = userService.findChargeList(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    //商务对接人(合同模块)", notes = "商务对接人(合同模块)")
    @GetMapping("/findBusinessList")
    public Result<List<User>> findBusinessList() {
        List<User> list = userService.findBusinessList();
        return new ResultUtil<List<User>>().setData(list);
    }

    //通过ID查询", notes = "通过ID查询")
    @GetMapping("/findById")
    public Result<User> findById(String id) {
        User user = userService.getById(id);
        if (user != null) {
            //拼接头像
            user.setAvatar(fileReadPath + user.getAvatar());
        }
        return new ResultUtil<User>().setData(user);
    }

    @RepeatSubmit
    //添加", notes = "添加用户")
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        userService.saveUser(user);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //修改", notes = "修改用户信息")
    @PostMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateUser(user);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //删除", notes = "删除【逻辑删除】")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        User user = new User();
        user.setId(id);
        user.setIs_delete("1");
        userService.updateById(user);
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        userRoleService.remove(queryWrapper);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //批量删除", notes = "批量删除")
    //(name = "ids", value = "格式:[1,2,3]", dataType = "Array", required = true, paramType = "body")
    @PostMapping("/deleteBatch")
    public Result delete(@RequestBody String[] ids) {
        List<User> list = new ArrayList<>();
        for (String id : ids) {
            User user = userService.getById(id);
            if (user != null) {
                user.setIs_delete("1");
                list.add(user);
            }
        }
        if (list.size() > 0) {
            userService.updateBatchById(list);
        }
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getCode());
    }

    //修改密码", notes = "修改密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, Object> models) {
        String user_id = JsonUtils.objToJson(models.get("user_id"));
        String old_password = JsonUtils.objToJson(models.get("old_password"));
        String new_password = JsonUtils.objToJson(models.get("new_password"));
        User user = userService.getById(user_id);
        //密码加密规则：数据库密码(password)+盐(salt),进行MD5加密
        if (!user.getPassword().equals(MD5Util.MD5(old_password + user.getSalt()))) {
            //旧密码不正确
            return new ResultUtil<>().setErrorMsg(ResultEnums.OLD_PASSWORD_ERROR.getCode(), ResultEnums.OLD_PASSWORD_ERROR.getReasonPhraseCN());
        }
        user.setPassword(MD5Util.MD5(new_password + user.getSalt()));
        boolean boo = userService.updateById(user);
        if (boo) {
            String user_name = user.getUser_name();
            // 清除 redis 数据
            //清除token
            Boolean delToken = redisTemplate.delete(SysConstant.REDIS_ACCESS_TOKEN + user_name);
            //清除角色
            // Boolean delRoles = redisTemplate.delete(SysConstant.REDIS_ROLE + user_name);
            //清除account_login_num
            Boolean numDelete = redisTemplate.delete(SysConstant.REDIS_ACCOUNT_LOGIN_NUM + user_name);
            //重置密码成功
            return new ResultUtil<>().setSuccessMsg(ResultEnums.UPDATE_PASSWORD_SUCCESSFULLY.getReasonPhraseCN());
        } else {
            //重置密码失败
            return new ResultUtil<>().setErrorMsg(ResultEnums.UPDATE_PASSWORD_FAILED.getCode(), ResultEnums.UPDATE_PASSWORD_FAILED.getReasonPhraseCN());
        }
    }


    //重置密码", notes = "重置密码")
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody Map<String, Object> models) {
        String user_id = JsonUtils.objToJson(models.get("user_id"));
        String password = JsonUtils.objToJson(models.get("password"));
        User user = userService.getById(user_id);
        user.setPassword(MD5Util.MD5(password + user.getSalt()));
        boolean boo = userService.updateById(user);
        if (boo) {
            String user_name = user.getUser_name();
            // 清除 redis 数据
            //清除token
            Boolean delToken = redisTemplate.delete(SysConstant.REDIS_ACCESS_TOKEN + user_name);
            //清除角色
            // Boolean delRoles = redisTemplate.delete(SysConstant.REDIS_ROLE + user_name);
            //清除account_login_num
            Boolean numDelete = redisTemplate.delete(SysConstant.REDIS_ACCOUNT_LOGIN_NUM + user_name);
            //重置密码成功
            return new ResultUtil<>().setSuccessMsg(ResultEnums.PASSWORD_RESET_SUCCESSFULLY.getReasonPhraseCN());
        } else {
            //重置密码失败
            return new ResultUtil<>().setErrorMsg(ResultEnums.PASSWORD_RESET_FAILED.getCode(), ResultEnums.PASSWORD_RESET_FAILED.getReasonPhraseCN());
        }
    }


    //是否禁用", notes = "是否禁用")
    @PostMapping("/isDisable")
    public Result isDisable(@RequestBody User user) {
        boolean boo = userService.updateById(user);
        if (boo) {
            return new ResultUtil<>().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil<>().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //获取当前用户信息", notes = "获取当前用户信息")
    @PostMapping("/getUserInfo")
    public Result<User> getUserInfo() {
        String user_id = this.getLoginUser().getId();
        User user = userService.getById(user_id);
        if (StringUtil.isNotEmpty(user.getMain_dept())) {
            Depart byId = departService.getById(user.getMain_dept());
            if (byId != null) {
                user.setMain_dept_name(byId.getName());
            }
        }
        //拼接头像
        user.setAvatar(fileReadPath + user.getAvatar());
        List<Depart> departs = userService.getDepartsByUserId(user_id);
        user.setDepts(departs);
        List<Role> roles = userService.getRolesByUserId(user_id);
        user.setRoles(roles);
        user.setGroup_ids(this.getGroupIds());
        return new ResultUtil<User>().setData(user);
    }

    //个人中心-修改用户信息", notes = "个人中心-修改用户信息")
    @PostMapping("/personalUpdate")
    public Result personalUpdate(@RequestBody User user) {
        VerifyUtil.notEmpty("数据序号", user.getId());
        User u = new User();
        u.setId(user.getId());
        u.setAvatar(user.getAvatar());// 头像
        u.setPhone(user.getPhone());//  手机号
        u.setEmail(user.getEmail());//邮箱
        userService.updateById(u);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }


    //修改用户状态", notes = "修改用户状态")
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody User user) {
        VerifyUtil.notEmpty("数据序号", user.getId());
        VerifyUtil.notEmpty("用户状态", user.getStatus());
        userService.updateById(user);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //通过用户IDList查询所有用户（查询统计需要）", notes = "通过用户IDList查询所有用户")
    @GetMapping("/findUserPage")
    public Result<IPage<User>> findUserPage(@ModelAttribute PageVo pageVo, @ModelAttribute User user) {
        return userService.findUserList(pageVo, user);
    }

    @GetMapping("/findDepartsByUserId")
    public Result<List<Depart>> getDepartsByUserId(String id) {
        List<Depart> list = userService.getDepartsByUserId(id);
        return new ResultUtil<List<Depart>>().setData(list);
    }


    @PostMapping("/findUserByDeparts")
    public Result<List<User>> getUserByDeparts(@RequestBody User user) {
        List<User> list = userService.findUserByDeparts(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    @GetMapping("/findUserInfoByUserId")
    public Result<Map<String, Object>> getUserInfoByUserId() {
        Map<String, Object> map = userService.getUserInfoByUserId(this.getLoginUser().getId());
        return new ResultUtil<Map<String, Object>>().setData(map);
    }

    @GetMapping("/findUserInfoByUserPage")
    public Result<IPage<User>> findUserInfoByUserIdPage(@ModelAttribute PageVo pageVo, @ModelAttribute User user) {
        user.setId(this.getLoginUser().getId());
        IPage<User> page = userService.findUserInfoByUserPage(PageUtil.initMpPage(pageVo), user);
        return new ResultUtil<IPage<User>>().setData(page);
    }

    //生成临时密码", notes = "生成临时密码")
    @PostMapping("/temporaryPassword")
    public Result temporaryPassword(@RequestBody Map<String, Object> models) {
        String user_id = JsonUtils.objToJson(models.get("user_id"));
        String real_name = JsonUtils.objToJson(models.get("real_name"));
        String user_code = JsonUtils.objToJson(models.get("user_code"));
        Integer duration = Integer.valueOf(models.get("duration") + "");
        VerifyUtil.notEmpty("用户编号", user_code);
        VerifyUtil.notEmpty("有效期", duration);
        String temporaryPassword = SysConstant.TEMPORARY_PASSWORD_PREFIX + StringUtil.randomString(4);
        redisTemplate.opsForValue().set(SysConstant.REDIS_TEMPORARY_PASSWORD + user_code, temporaryPassword, duration, TimeUnit.HOURS);
        return new ResultUtil<>().setData(temporaryPassword);
    }


    @GetMapping("/getUserByDepartsOrderByDepartIdAndUserId")
    public Result<List<User>> getUserByDepartsOrderByDepartIdAndUserId(String departs) {
        List<User> list = userService.getUserByDepartsOrderByDepartIdAndUserId(departs);
        return new ResultUtil<List<User>>().setData(list);
    }


    //根据depart_id查询部门负责人", notes = "根据depart_id查询部门负责人")
    @GetMapping("/findBMFZRByDepartId")
    public Result<User> findBMFZRByDepartId(String depart_id) {
        User user = userService.findBMFZRByDepartId(depart_id);
        return new ResultUtil<User>().setData(user);
    }

//    //导出菜单
//    @PostMapping("/exportMenus")
//    public void exportMenus(HttpServletResponse response, @RequestBody Map<String, Object> map) throws IOException {
//        userService.exportMenus(response, map);
//    }
//
//    //导出菜单详细
//    @PostMapping("/exportMenuDetails")
//    public void exportMenuDetails(HttpServletResponse response, @RequestBody Map<String, Object> map) throws IOException {
//        userService.exportMenuDetails(response, map);
//    }
//
//    //根据sys_dict配置信息查询用户信息", notes = "根据sys_dict配置信息查询用户信息")
//    @GetMapping("/findBySysDict")
//    public Result<List<User>> findBySysDict(String code) {
//        List<User> users = userService.findBySysDict(code);
//        return new ResultUtil<List<User>>().setData(users);
//    }

    // 获取用户信息
    @GetMapping("/getRoleDetailsByUserId")
    public Result<JSONArray> getRoleDetailsByUserId(@RequestParam String userId) {
        JSONArray details = userService.getRoleDetailsByUserId(userId);
        return new ResultUtil<JSONArray>().setData(details);
    }

//    @PostMapping("/getOnlineUserPage")
//    public Result<IPage<User>> getOnlineUserPage(@RequestBody Map<String, Object> map) {
//        PageVo pageVo = JsonUtils.mapToObj(map, PageVo.class);
//        User user = JsonUtils.mapToObj(map, User.class);
//        IPage<User> page = userService.findOnlineUserPage(PageUtil.initMpPage(pageVo), user);
//        return new ResultUtil<IPage<User>>().setData(page);
//    }

    @GetMapping("/findPersonsByGroups")
    public Result<List<User>> getPersonsByGroups(@ModelAttribute User user) {
        List<User> list = userService.getPersonsByGroups(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    //根据部门id找到参与合同统计的人员", notes = "根据部门id找到参与合同统计的人员")
    @PostMapping("/getStatisticUser")
    public Result<List<User>> getStatisticUser(@RequestBody User user) {
        List<User> list = userService.getStatisticUser(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    //根据部门id找到参与九州合同统计的人员", notes = "根据部门id找到参与九州合同统计的人员")
    @PostMapping("/getJiuzhouStatisticUser")
    public Result<List<User>> getJiuzhouStatisticUser(@RequestBody User user) {
        List<User> list = userService.getJiuzhouStatisticUser(user);
        return new ResultUtil<List<User>>().setData(list);
    }

    //修改", notes = "修改用户信息")
    @PostMapping("/updateById")
    public Result updateById(@RequestBody User user) {
        VerifyUtil.notEmpty("id",user.getId());
        userService.updateById(user);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

//    //通过人员角色查询九州的人员", notes = "通过人员角色查询九州的人员")
//    @GetMapping("/getJiuzhouByRoleId")
//    public Result<List<User>> getJiuzhouByRoleId() {
//        List<User> list = userService.getJiuzhouByRoleId();
//        return new ResultUtil<List<User>>().setData(list);
//    }

    //通过用户查询角色信息", notes = "通过用户查询角色信息")
    @GetMapping("/findRolesByUserId")
    public Result<Role> findRolesByUserId(String user_id) {
        List<Role> roles = userService.findRolesByUserId(user_id);
        return new ResultUtil().setData(roles);
    }

//    //根据部门id找到该部门的院长", notes = "根据部门id找到该部门的院长")
//    @GetMapping("/getDirectorByDepartId")
//    public Result<List<User>> getDirectorByDepartId(String departId, String positionCode) {
//        List<User> list = userService.getDirectorByDepartId(departId, positionCode);
//        return new ResultUtil<List<User>>().setData(list);
//    }

    //根据real_name找到用户信息", notes = "根据real_name找到用户信息")
    @GetMapping("/findUserByRealName")
    public Result<List<User>> findUserByRealName(@ModelAttribute User user) {
        List<User> list = userService.findUserByRealName(user);
        return new ResultUtil<List<User>>().setData(list);
    }
}
